<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\CountryModel;
use App\MovieModel;
use App\TypeModel;
use App\TypeTableMode;
use Illuminate\Http\Request;
use mysql_xdevapi\Result;

class MovieController extends Controller
{
    public function kino(Request $request)
    {
        $page=$request->input("page");
        $size=10;
        $offset=($page-1)*$size;
        $movieCount=MovieModel::count();
        $maxPage=ceil($movieCount/$size);
//        $movie=MovieModel::get();
        $cols=["movie.*","type.name_ch as typeName","country.name_ch as countryName"];
        $movies=MovieModel::leftjoin("type","movie.type","type.id")->leftjoin("country","movie.country","country.id")->orderBy("id","ASC")->offset($offset)->take($size)->get($cols);
        return view("admin.movie",compact("movies","page","maxPage"));
    }

    public function movieaddpage(Request $request)
    {
        $id=$request->input("id");
        $movie=MovieModel::find($id);
        $types = TypeTableMode::get();
        $countries = CountryModel::get();
        return view("admin.movieaddpage", compact("movie", "countries","types"));
    }

    public function movieupdate(Request $request)
    {

        $id=$request->input("id");
        $movie=MovieModel::find($id);
        $types = TypeTableMode::get();
        $countries = CountryModel::get();
        return view("admin.movieupdate",compact("movie","types","countries"));
    }


    public function movieaddinsert(Request $request)
    {
        try {
            $input=$request->input();
            unset($input['_token']);
            $img=$request->file("img");
            if($img){
                $imgName="img_".date("Y_m_d")."_".rand(1,1000).".".$img->getClientOriginalExtension();
                $img->move(public_path("img"),$imgName);
                $input['img']="img/".$imgName;
            }
            $movie=$request->file("movie");
            if($movie) {
            $movieName="movie_".date("Y_m_d")."_".rand(1,1000).".".$movie->getClientOriginalExtension();
                $movie->move(public_path("movies"),$movieName);
                $input['movie']="movies/".$movieName;
            }
            $input['score']*=10;
//            dd($input);
            $movie=MovieModel::find($input['id']);
            MovieModel::create($input);
            if($movie){
                return back()->with("result","OK");
            }
        }catch(\Exception $e){
//            dd($e->getMessage()."***".$e->getLine());
            return back()->with("result","NO");
        }

    }


    public function moviedel(Request $request)
    {
        $id=$request->input('id');
        $ok=MovieModel::where("id",$id)->delete();
        if($ok){
            $result=["title"=>"删除成功！","err"=>0];
            return json_encode($result);
        }else{
            $result=["title"=>"删除失败！","err"=>0];
            return json_encode($result);
        }
    }

}

